<template>
  <el-card class="userAvatar-container">
    <!-- 面板屑导航 -->
     <el-breadcrumb separator-class="el-icon-arrow-right" style="marginBottom:15px">
        <el-breadcrumb-item :to="{ path: '/' }"
          ><i class="el-icon-s-home"></i> 首页</el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><i class="el-icon-share"></i> 个人中心</el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><i class="el-icon-share"></i> 更换头像</el-breadcrumb-item
        >
      </el-breadcrumb>
    <!-- 用来展示头像的盒子 -->
    <div class="avatar-box">
      <img :src=" defaultImg" />
    </div>
    <div>
      <el-button type="primary" class="el-icon-plus" @click="$refs.fileRef.click()"
        >选择图片</el-button
      >
      <el-button type="success" class="el-icon-upload" :disabled="isDisabled" @click="pgupSubmit">上传头像</el-button>
      <input type="file" ref="fileRef" @change="changeAvatar" hidden />
    </div>
  </el-card>
</template>

<script>
import defaultImg from '@/assets/images/avatar.jpg'
import { reqUpdateAvatar } from '@/api/user'
export default {
  name: 'UserAvatar',
  data () {
    return {
      defaultImg: defaultImg, // 默认封面
      isDisabled: true
    }
  },
  methods: {
    changeAvatar (e) {
      console.log(e.target.files[0])
      const file = e.target.files[0]
      if (file) {
        const fd = new FileReader()
        // console.log(fd)
        fd.readAsDataURL(file)
        fd.onload = () => {
          this.defaultImg = fd.result
          this.isDisabled = false
        }
      }
    },
    async pgupSubmit () {
      const { data } = await reqUpdateAvatar(this.defaultImg)
      if (data.code !== 0) return this.$message.error(data.message)
      this.$message.success(data.message)
      this.$store.dispatch('user/getUserInfo')
    }
  }
}
</script>
<style lang="less" scoped>
.userAvatar-container {
  padding: 0 0 20px 20px;

  .avatar-box {
    img {
      width: 350px;
      height: 350px;
      object-fit: cover;
    }
  }

  .btns {
    padding-top: 10px;
  }
}
</style>
